package com.ckerchina.admin.ckadmin.service;

import com.ckerchina.admin.ckadmin.dao.DbQRTicketResultDAO;
import com.ckerchina.admin.ckadmin.dao.WxUserDAO;
import com.ckerchina.admin.ckadmin.domain.WXUser;
import com.ckerchina.admin.ckadmin.service.wx.*;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;

/**
 * Created by 晓丰 on 2016/1/9.
 */
@Service
public class WxPublicService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${wx.public.appid}")
    String publicAppid;
    @Value("${wx.public.secret}")
    String publicSecret;

    @Autowired
    WxUserDAO wxUserDAO;

    @Autowired
    DbQRTicketResultDAO dbQRTicketResultDAO;

    public WXUser getWxUserByOpenid(String openid) throws IOException {
        String url="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+this.getBaseWxAccessResult()+"&openid="+openid+"&lang=zh_CN";
        String userResult = new String(Request.Get(url).execute().returnContent().asBytes(),"UTF-8");
        logger.info("requesting {},result is {}",url,userResult);
        return new ObjectMapper().readValue(userResult, WXUser.class);
    }

    public String getBaseWxAccessResult() throws IOException {

        String url1="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ publicAppid +"&secret="+ publicSecret;
        String result = Request.Get(url1).execute().returnContent().asString();
        logger.info("获取微信access token，url is {},and result is {}",url1,result);
        WxAccessResult resultMap = new ObjectMapper().readValue(result, WxAccessResult.class);
        if(resultMap.getErrcode()!=0){
            logger.error("获取微信access token，url is {},and errorcode is {}, and errormsg is ",url1,resultMap.getErrcode(),resultMap.getErrmsg());
            throw new RuntimeException("获取微信access token 失败"+resultMap.getErrcode()+":"+resultMap.getErrmsg());
        }
        return resultMap.getAccess_token();
    }

    public String getPublicAuthenticationUrl(String url) {
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+publicAppid+"&redirect_uri=" + url + "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
    }

    public DbQRTicketResult getQrCode(long scene_id) throws IOException {
        DbQRTicketResult dbQRTicketResult = dbQRTicketResultDAO.find(scene_id);
        if(dbQRTicketResult!=null){
            if(new Date().getTime()>(dbQRTicketResult.getExpire_time()+592000*1000)){
                QRTicketResult qrTicketResult = getQrTicketResultFromWeb(scene_id);
                dbQRTicketResult.setTicket(qrTicketResult.getTicket());
                dbQRTicketResult.setExpire_time(new Date().getTime()+qrTicketResult.getExpire_seconds()*1000);
                dbQRTicketResultDAO.merge(dbQRTicketResult);
            }
            return dbQRTicketResult;
        }
        QRTicketResult qrTicketResult = getQrTicketResultFromWeb(scene_id);
        dbQRTicketResult=new DbQRTicketResult();
        dbQRTicketResult.setId(scene_id);
        dbQRTicketResult.setTicket(qrTicketResult.getTicket());
        dbQRTicketResult.setUrl(qrTicketResult.getUrl());
        dbQRTicketResult.setExpire_time(new Date().getTime()+qrTicketResult.getExpire_seconds()*1000);
        dbQRTicketResultDAO.persist(dbQRTicketResult);
        return dbQRTicketResult;
    }

    private QRTicketResult getQrTicketResultFromWeb(long scene_id) throws IOException {
        String uri = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + this.getBaseWxAccessResult();
        String result = Request.Post(uri).bodyString("{\"expire_seconds\": 2592000, \"action_name\": \"QR_SCENE\", \"action_info\": {\"scene\": {\"scene_id\": " + scene_id + "}}}", ContentType.APPLICATION_JSON).execute().returnContent().asString();
        logger.info("request qr ticket url is {},and result is {}",uri,result);
        return new ObjectMapper().readValue(result, QRTicketResult.class);
    }

    public String getSelfMenu() throws IOException {
        String uri="https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token="+this.getBaseWxAccessResult();
        return new String(Request.Get(uri).execute().returnContent().asBytes(),"utf-8");
    }

    public String getMenu() throws IOException {
        String uri="https://api.weixin.qq.com/cgi-bin/menu/get?access_token="+this.getBaseWxAccessResult();
        return new String(Request.Get(uri).execute().returnContent().asBytes(),"utf-8");
    }
    
    public String setMenu(String menu) throws IOException {
        String uri="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+this.getBaseWxAccessResult();
        return new String(Request.Post(uri).bodyString(menu,ContentType.APPLICATION_JSON).execute().returnContent().asBytes(),"utf-8");
    }
    
    public String deleteMenu() throws IOException {
        String uri="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="+this.getBaseWxAccessResult();
        return new String(Request.Get(uri).execute().returnContent().asBytes(),"utf-8");
    }
}
